/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sgs.dao;

import br.com.sgs.entity.Instituicao;
import java.util.List;
import javax.persistence.Query;

/**
 *
 * @author Eric
 */
public class DAOInstituicao extends AbstractDAO implements IDAOInstituicao {
    
    public DAOInstituicao(){
        super();
    }
    
    @Override
    public Instituicao findInstituicaoById(int idinstituicao) {
        try {

            Query q = em.createQuery("SELECT i FROM Instituicao i WHERE i.id = :idinstituicao");
            q.setParameter("idinstituicao", idinstituicao);
            return (Instituicao) q.getSingleResult();

        } catch (Exception e) {
            System.err.println("Erro no findInstituicaoById");
            return null;
        }
    }
   
    @Override
    public List<Instituicao> findInstituicaoByAll(String nome, String nomefantasia, String cnpj, List<String> lsstatus) {

        try {

            StringBuilder sql = new StringBuilder();

            if (!nome.equals("")) {
                sql.append("  AND UPPER(i.nome) LIKE '%").append(nome.toUpperCase()).append("%'");
            }

            if (!nomefantasia.equals("")) {
                sql.append("  AND UPPER(i.nomefantasia) LIKE '%").append(nomefantasia.toUpperCase()).append("%'");
            }

            if (!cnpj.equals("")) {
                sql.append("  AND UPPER(i.cnpj) LIKE '%").append(cnpj.toUpperCase()).append("%'");
            }

            if (!lsstatus.isEmpty()) {
                String status = "";
                for (String st : lsstatus) {
                    status += st + ",";
                }
                status += lsstatus.get(0).toString();
                sql.append(" AND i.status  IN (").append(status).append(")");
            }
            
            Query q = em.createQuery("SELECT i FROM Instituicao i WHERE i.id > 0 " + sql.toString() + " ORDER BY i.nome ASC");

            return q.getResultList();

        } catch (Exception e) {
            System.err.println("Erro na consulta findInstituicaByAll");
            e.printStackTrace();
            return null;
        }
        
        
    }
}
